package com.seeyon.bugfixtools.workflow.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.google.gson.Gson;
import com.seeyon.bugfixtools.form.dao.FormDao;
import com.seeyon.bugfixtools.form.dto.FormBizInfo;
import com.seeyon.bugfixtools.workflow.constants.WorkflowProcessKey;
import com.seeyon.bugfixtools.workflow.dao.WorkflowAuthDao;
import com.seeyon.bugfixtools.workflow.dao.WorkflowLockDao;
import com.seeyon.bugfixtools.workflow.dto.ScanLockResDto;
import com.seeyon.bugfixtools.workflow.dto.WarningAuthDto;
import com.seeyon.bugfixtools.workflow.dto.WorkflowTemplateInfo;
import com.seeyon.bugfixtools.workflow.dto.WorkflowXmlBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author cans
 * @date 2024/5/3
 **/
@Service
public class WorkflowService {

    private static final Logger logger = LoggerFactory.getLogger(WorkflowService.class);

    @Resource
    private WorkflowLockDao workflowLockDao;
    @Resource
    private WorkflowAuthDao workflowAuthDao;
    @Resource
    private FormDao formDao;


    /**
     * 扫描锁信息
     *
     * @return
     */
    public List<ScanLockResDto> scanLock() {
        return workflowLockDao.scanLock();
    }
    public void updateAuthRepair() {
        // 1.查询问题数据
        List<WarningAuthDto> warningAuthList = workflowAuthDao.getWarningAuth();
        logger.info("问题数据条数:" + warningAuthList.size());
        System.out.println("--------------处理权限问题开始---------------");
        for (WarningAuthDto warningAuth : warningAuthList) {
            // 删除旧的权限
            workflowAuthDao.deleteAuthMappingByResourceIdAndViewId(warningAuth.getAuthResourceId(), warningAuth.getViewId());
            // 将权限映射指向旧的权限ID
            workflowAuthDao.updateAuthMappingResourceIdById(warningAuth.getAuthMappingId(), warningAuth.getOldResourceId());
            // 删除新权限的信息
            workflowAuthDao.deleteAuthInfoByResourceId(warningAuth.getAuthResourceId());
        }
        System.out.println("--------------处理权限问题结束---------------");
    }


    public void doUnLock(Long lockId) {
        workflowLockDao.deleteLock(lockId);
    }

    public void scanWarningAuth() throws JsonProcessingException {
        List<WorkflowTemplateInfo> workflowTemplateInfoList = workflowAuthDao.getAllTemplateInfo();
        for (WorkflowTemplateInfo workflowTemplateInfo : workflowTemplateInfoList) {
            // 将xml转换为json数据
            String jsonString = this.xmlToJson(workflowTemplateInfo.getWorkflowXml());
            FormBizInfo formBizInfo = formDao.getFormBizInfoByFormId(workflowTemplateInfo.getFormId());
            logger.info("应用包:" + formBizInfo.getBizName() + ",表单:" + formBizInfo.getFormName() + workflowTemplateInfo.getWorkflowTemplateId() + "_" + workflowTemplateInfo.getTemplateName() + "___模板JSON数据:" + jsonString);
            Gson gson = new Gson();
            // 将JSON字符串转换为Java对象
            Map map = gson.fromJson(jsonString, Map.class);
            Map<String,Object> workflowDataMap = (Map<String,Object>)map.get("p");
            Object nodeDataList = workflowDataMap.get("n");
            if(nodeDataList instanceof List){
                List<Object> nodeDataList1 = (List<Object>)nodeDataList;
                for (Object nodeDataTmp : nodeDataList1) {
                    if(nodeDataTmp instanceof Map){
                      Map<String,Object>  nodeData = (Map<String,Object>) nodeDataTmp;
                        Object formAuthViewDataTemp = nodeData.get("s");
                        Object nodeName = nodeData.get("n");
                        if(formAuthViewDataTemp instanceof Map){
                            Map<String,String>  formAuthViewData = (Map<String,String>) formAuthViewDataTemp;
                            String authFormId = formAuthViewData.get("f");
                            String viewAuthId = formAuthViewData.get("fv");
                            logger.info("节点名称:" + nodeName +  ",表单ID:" + authFormId + ",视图权限ID: " + viewAuthId);
                        }
                        logger.info(nodeData.toString());
                    }
                }
            }

        }
    }

    private String xmlToJson(String workflowXml) throws JsonProcessingException {
        if(workflowXml == null || workflowXml.isEmpty()){
            return "";
        }
        // 创建XmlMapper
        XmlMapper xmlMapper = new XmlMapper();

        JsonNode jsonNode = xmlMapper.readTree(workflowXml);
        // 将JsonNode转换为JSON字符串
        for (JsonNode node : jsonNode) {
            logger.info(node.toString());
        }
        return jsonNode.toString();
    }

    private WorkflowXmlBean xmlToWorkflowXmlBean(String workflowXml) throws JsonProcessingException {
        WorkflowXmlBean workflowXmlBean = new WorkflowXmlBean();
        if(workflowXml == null || workflowXml.isEmpty()){
            return workflowXmlBean;
        }
        // 创建XmlMapper
        XmlMapper xmlMapper = new XmlMapper();

        JsonNode jsonNode = xmlMapper.readTree(workflowXml);
        JsonNode processNode = jsonNode.get(WorkflowProcessKey.PROCESS);
        JsonNode jsonNode1 = processNode.get(WorkflowProcessKey.NODE);


        // 将JsonNode转换为JSON字符串
        return workflowXmlBean;
    }

}
